/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package web;

import ejb.entity.Compte;
import ejb.entity.Operations;
import ejb.entity.OperationsBatch;
import ejb.facade.CompteFacadeRemote;
import ejb.facade.OperationsBatchFacadeRemote;
import ejb.facade.OperationsFacadeRemote;
import java.io.IOException;
import java.util.Date;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author chulin
 */
@WebServlet(name = "LaunchOperationsBatch", urlPatterns = {"/LaunchOperationsBatch"})
public class LaunchOperationsBatch extends HttpServlet {

    @EJB
    private CompteFacadeRemote compteFacade;
    @EJB
    private OperationsBatchFacadeRemote operationsBatchFacade;
    @EJB
    private OperationsFacadeRemote operationsFacade;
    @Resource(mappedName = "jms/UpdateOperationMessageFactory")
    private ConnectionFactory operationConnectionFactory;
    @Resource(mappedName = "jms/UpdateOperationMessage")
    private Queue operationQueue;
    @Resource(mappedName = "jms/UpdateCompteMessageFactory")
    private ConnectionFactory compteConnectionFactory;
    @Resource(mappedName = "jms/UpdateCompteMessage")
    private Queue compteQueue;
    @Resource(mappedName = "jms/DeleteOperationsBatchMessageFactory")
    private ConnectionFactory operationBatchConnectionFactory;
    @Resource(mappedName = "jms/DeleteOperationsBatchMessage")
    private Queue operationBatchQueue;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            for (OperationsBatch operationBatch : operationsBatchFacade.findAll()) {

                // Mise a jour de l'operation
                //
                Connection connection = operationConnectionFactory.createConnection();
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                MessageProducer messageProducer = session.createProducer(operationQueue);
                ObjectMessage message = session.createObjectMessage();

                Operations operation = operationsFacade.find(operationBatch.getIdOperation());
                operation.setDateDExecution(new Date());

                message.setObject(operation);
                messageProducer.send(message);
                messageProducer.close();
                session.close();
                connection.close();

                // Mise a jour des comptes
                //
                connection = compteConnectionFactory.createConnection();
                session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                messageProducer = session.createProducer(compteQueue);
                message = session.createObjectMessage();

                Compte compte_source = compteFacade.find(operation.getIdCompteSource());
                Compte compte_cible = compteFacade.find(operation.getIdCompteCible());

                if ("Retrait".equals(operation.getTypeOperation())) {
                    compte_source.setSolde(compte_source.getSolde() - operation.getMontant());
                }
                if ("Credit".equals(operation.getTypeOperation())) {
                    compte_source.setSolde(compte_source.getSolde() + operation.getMontant());
                }
                if ("Virement".equals(operation.getTypeOperation()) && compte_cible != null) {
                    compte_source.setSolde(compte_source.getSolde() - operation.getMontant());
                    compte_cible.setSolde(compte_cible.getSolde() + operation.getMontant());
                    compte_cible.setDateSolde(new Date());

                    message.setObject(compte_cible);
                    messageProducer.send(message);
                }
                compte_source.setDateSolde(new Date());

                message.setObject(compte_source);
                messageProducer.send(message);
                messageProducer.close();
                session.close();
                connection.close();

                // Suppression du batch
                //
                connection = operationBatchConnectionFactory.createConnection();
                session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                messageProducer = session.createProducer(operationBatchQueue);
                message = session.createObjectMessage();
                message.setObject(operationBatch.getIdOperation());
                messageProducer.send(message);
                messageProducer.close();
                session.close();
                connection.close();
            }
            response.sendRedirect("ListClient");
        } catch (JMSException ex) {
            ex.printStackTrace();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
